package com.skit.main.fragment

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.*
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.request.RequestOptions
import com.skit.common.base.BaseFragment
import com.skit.common.bean.ActivityBean
import com.skit.common.config.RetrofitClient
import com.skit.common.config.RouteConfig
import com.skit.common.http.HttpUtils
import com.skit.common.ktx.NetResultKtx.initData
import com.skit.common.manager.UserManager
import com.skit.common.utils.ToastUtils
import com.skit.main.adapter.MainRecyclerViewBannerAdapter
import com.skit.main.adapter.TypeRecyclerViewAdapter
import com.skit.main.bean.RecyclerTypeBean
import com.skit.main.databinding.MainFragmentHomeBinding
import com.skit.common.retrofit.ActivityProtocol
import com.skit.main.viewmodels.HomeActivityViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.main_fragment_home.*
import java.util.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/5/9
 */

@AndroidEntryPoint
class HomeActivityFragment : BaseFragment() {

    val viewModel: HomeActivityViewModel by viewModels()

    private lateinit var binding: MainFragmentHomeBinding
    private lateinit var bannerAdapter: MainRecyclerViewBannerAdapter
    private lateinit var rootView: View
    override val statusPadding = false
    lateinit var activityAdapter: TypeRecyclerViewAdapter

    private val requestOption = RequestOptions.circleCropTransform()
    private val activityList: MutableList<ActivityBean> = ArrayList()
    private val recyclerViewData: MutableList<RecyclerTypeBean> = ArrayList()
    private val bannerList: MutableList<String> = ArrayList()

    public lateinit var scrollGJ: (Int) -> Unit

    companion object {
        const val TAG = "HomeFragment"
        fun newInstance(): HomeActivityFragment {
            val fragment = HomeActivityFragment()
            val bundle = Bundle()

            fragment.arguments = bundle
            return fragment
        }
    }


    override fun initConfig() {
        super.initConfig()
        viewModel.activityLiveData.observe(this) {
            it.initData({
                binding.refreshLayout.isRefreshing = false
                ToastUtils.showToast("请求失败")
                binding.loadingTV.apply {
                    text = "请求失败、点击重试"
                    setOnClickListener {
                        getData()
                        viewModel.getActivity(10, 10, 1)
                    }
                }
                binding.progressBar.visibility = View.GONE
            }, {
                binding.refreshLayout.isRefreshing = false
                binding.loading.visibility = View.GONE
                binding.loadingTV.setOnClickListener {}
                bannerList.clear()
                activityList.apply {
                    clear()
                    addAll(data)
                }

                recyclerViewData.add(
                    RecyclerTypeBean(
                        "推荐活动",
                        RecyclerView.HORIZONTAL,
                        RecyclerTypeBean.LayoutManager.LINEAR_LAYOUT_MANAGER,
                        activityList,
                        RecyclerTypeBean.Type.ACTIVITY_HOLDER
                    ).apply {
                        backGroundColor = Color.TRANSPARENT
                        scroll = true
                    }
                )
                recyclerViewData.add(
                    RecyclerTypeBean(
                        "推荐活动",
                        RecyclerView.VERTICAL,
                        RecyclerTypeBean.LayoutManager.LINEAR_LAYOUT_MANAGER,
                        activityList,
                        RecyclerTypeBean.Type.ACTIVITY_HOLDER
                    ).apply {
                        backGroundColor = Color.WHITE
                        scroll = false
                    }
                )

                data.filterIndexed { index, activityBean -> index < 4 }.also { list ->
                    list.forEach { bean ->
                        val first = bean.activityImages.first()
                        bannerList.add(first)
                    }
                }
                activityAdapter.notifyDataSetChanged()
                bannerAdapter.notifyDataSetChanged()
            })
        }

    }

    override fun initData() {
        super.initData()
        viewModel.getActivity(10, 10, 1)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = MainFragmentHomeBinding.inflate(inflater, container, false)
        rootView = binding.root//inflater.inflate(R.layout.main_fragment_home, container, false)
        return rootView
    }

    override fun onResume() {
        super.onResume()
        val user = UserManager.user
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        bannerAdapter = MainRecyclerViewBannerAdapter(bannerList)
        activityAdapter = TypeRecyclerViewAdapter(recyclerViewData).apply {
            onItemClickListener = object : (View, Int) -> Unit {
                override fun invoke(p1: View, p2: Int) {
                    Log.d(TAG, "invoke: ${activityList[p2]}")
                    ARouter.getInstance().build(RouteConfig.MainRoute.MAIN_ACTIVITY_DETAILS)
                        .withSerializable("bean", activityList[p2])
                        .navigation()
                }
            }
        }

        val mergeAdapter = MergeAdapter(bannerAdapter, activityAdapter)
        binding.recyclerView.apply {
            adapter = mergeAdapter
            layoutManager = LinearLayoutManager(activity)
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (this@HomeActivityFragment::scrollGJ.isInitialized) {
                        scrollGJ(dy)
                    }
                }
            })
        }

        binding.refreshLayout.setOnRefreshListener {
            getData()
        }
        getData()
    }

    private fun getData() {
        if (recyclerViewData.isEmpty()) {
            binding.loading.visibility = View.VISIBLE
            binding.progressBar.visibility = View.VISIBLE
            binding.loadingTV.text = "正在加载..."
        }

        val userProtocol: ActivityProtocol = RetrofitClient.getService(ActivityProtocol::class.java)
        val activityType = userProtocol.activityType;
        HttpUtils.doRequest(activityType) {
            if (it == null || !it.isSuccess) return@doRequest
            val data = it.data;
            val typeList: MutableList<String> = ArrayList()
            data.forEach { i ->
                i.name?.let { it1 -> typeList.add(it1) }
            }
            recyclerViewData.add(0,
                RecyclerTypeBean(
                    "活动类型",
                    RecyclerView.VERTICAL,
                    RecyclerTypeBean.LayoutManager.GRIDLAYOUT_MANAGER,
                    typeList,
                    RecyclerTypeBean.Type.TEXT_ICON_HOLDER
                ) {
                    ARouter.getInstance().build(RouteConfig.MainRoute.MAIN_ACTIVITY_TYPES)
                        .navigation()
                }.apply {
                    backGroundColor = Color.WHITE
                    more = "更多"
                    scroll = false
                }
            )
            activityAdapter.notifyItemInserted(recyclerViewData.size)
        }
    }

}